package GUI;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

@SuppressWarnings("serial")
public class ControlPane extends JPanel implements ActionListener{
	private HoldemButton callBut, raiseBut, foldBut, checkBut;
	private int width, height;
	private final int BORDER_RADIUS = 10;
	private PokerTable players;
	private JPanel rightPanel;
	private PlayersPane playersPanel;
	private BiddingPane biddingPanel;
	
	public ControlPane(PokerTable players, int width, int height){
		super();
		this.width = width - BORDER_RADIUS;
		this.height = height - BORDER_RADIUS;
		this.players =  players;
		this.setBorder(BorderFactory.createMatteBorder(4, 4, 40, 4, Color.GRAY));
		this.setLayout(new BorderLayout());
		this.setBackground(Color.GRAY);
		this.setSize(this.width, this.height);
		this.setAlignmentY(JPanel.LEFT_ALIGNMENT);
		this.initializePanels();
		this.addButtons();
		this.addCashField();
	}
	private void initializePanels(){
		playersPanel = new PlayersPane(players);
		rightPanel = new JPanel();
		rightPanel.setLayout(new BoxLayout(rightPanel, BoxLayout.Y_AXIS));
		add(playersPanel, BorderLayout.WEST);
		add(rightPanel, BorderLayout.CENTER);
	}
	
	private void addButtons(){
		callBut = new HoldemButton(Options.CALL, Color.GREEN);
		raiseBut = new HoldemButton(Options.RAISE, Color.GREEN);
		foldBut = new HoldemButton(Options.FOLD, Color.GREEN);
		checkBut = new HoldemButton(Options.CHECK, Color.GREEN);
		this.adaptListener();
		JPanel buttonsPane = new JPanel();
		buttonsPane.setLayout(new BoxLayout(buttonsPane, BoxLayout.X_AXIS));
		buttonsPane.add(callBut);
		buttonsPane.add(foldBut);
		buttonsPane.add(checkBut);
		buttonsPane.add(raiseBut);
		buttonsPane.setBorder(new EmptyBorder(20, 20, 10, 20));
		rightPanel.add(buttonsPane);
	}
	private void adaptListener(){
		callBut.addActionListener(this);
		foldBut.addActionListener(this);
		checkBut.addActionListener(this);
		raiseBut.addActionListener(this);
	}
	private void addCashField(){
		Player owner = new Player("NONE", -1, false);
		for(Player player:players){
			if(player.isOwner()){
				owner = player;
			}
		}
		biddingPanel = new BiddingPane(owner);
		add(biddingPanel, BorderLayout.EAST);
	}
	public void updatePlayers(PokerTable players){
		this.players = players;
		this.playersPanel.updatePlayers(players);
	}
	public PokerTable getPlayers(){
		return players;
	}
	@Override
	public void actionPerformed(ActionEvent arg0) {
		if(arg0.getSource() instanceof HoldemButton){
			HoldemButton source = (HoldemButton)arg0.getSource();
			if(source.equals(foldBut)){
				biddingPanel.notifyFold();
			}else if(source.equals(raiseBut)){
				biddingPanel.prepareBid();
			}else if(source.equals(callBut)){
				biddingPanel.propagateCall();
			}
		}
	}
}
